package com.ruoyi.resume.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.resume.domain.model.Mappings;
import com.ruoyi.resume.domain.model.SplitResumeResult;
import com.ruoyi.resume.domain.model.resumeProfile.BasicInfo;
import com.ruoyi.resume.domain.response.ResumeAndTagsResp;
import com.ruoyi.resume.domain.response.ResumeDetailsResponse;
import com.ruoyi.resume.domain.response.SimilarCandidateResp;
import com.ruoyi.resume.service.ResumeService;
import com.ruoyi.resume.utils.minIO.MinIOUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import static com.ruoyi.common.utils.PageUtils.startPage;

@Api(tags = "简历管理")
@RestController
@RequestMapping("/resume-management")
public class ResumeController extends BaseController {

    @Autowired
    private ResumeService resumeService;

    @Autowired
    private MinIOUtil minIOUtil;

    @ApiOperation(value = "分页获取简历[按姓名、性别、户籍、政治面貌筛选]")
    @GetMapping("/all")
    @Anonymous
    public TableDataInfo getResumesByRange(
            @RequestParam(required = false) String name, // 可选参数
            @RequestParam(required = false) String gender, // 可选参数
            @RequestParam(required = false) String nativePlace, // 可选参数
            @RequestParam(required = false) String politicalStatus, // 可选参数
            @RequestParam(required = false) Integer isOuter, // 可选参数
            @RequestParam(required = false) Integer status  // 可选参数
    ) {
        startPage();
        return resumeService.getResumesByRange(name,gender,nativePlace,politicalStatus,isOuter, status);

    }


    /**
     * 下载简历
     */
    @ApiOperation(value = "下载简历")
    @GetMapping("/download")
    @Anonymous
    public ResponseEntity<String> downloadResume(
            @ApiParam(value = "简历ID", required = true) @RequestParam int resumeId, HttpServletResponse response
    ) throws Exception {
        String objectName = resumeId + "/" + resumeId + ".pdf";
        try (InputStream fileStream = minIOUtil.downloadFileAsStream("resume", objectName)) {
            // 设置响应头触发下载
            response.setContentType("application/pdf");
            String filename = "resume_" + resumeId + ".pdf";
            response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

            // 将文件流写入响应
            IOUtils.copy(fileStream, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            // 处理异常，返回错误状态
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try {
                response.getWriter().write("下载失败: " + e.getMessage());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return ResponseEntity.ok("下载成功");
    }

    /**
     * 收藏简历
     */
    @ApiOperation(value = "收藏简历")
    @GetMapping("/collect")
    //@Anonymous
    public ResponseEntity<String> collectResume(
            @ApiParam(value = "简历ID", required = true) @RequestParam int resumeId
    ) {
        try{
            resumeService.collectResume(resumeId);
        }catch (Exception e){
            // 处理异常，返回错误状态
            return ResponseEntity.ok("收藏失败,请勿重复收藏");
        }
        return ResponseEntity.ok("收藏成功");

    }

    /**
     * 查询收藏的简历(根据条件)
     */
    @ApiOperation(value = "查询收藏的简历")
    @GetMapping("/all-collected")
    //@Anonymous
    public ResponseEntity<List<ResumeAndTagsResp>> getAllCollectedResumes(
            @RequestParam(required = false) String name, // 可选参数
            @RequestParam(required = false) String gender, // 可选参数
            @RequestParam(required = false) String nativePlace, // 可选参数
            @RequestParam(required = false) String politicalStatus // 可选参数
    ) {
        List<ResumeAndTagsResp> resumes = resumeService.getAllCollectedResumes(name,gender,nativePlace,politicalStatus);
        return ResponseEntity.ok(resumes);
    }

    /**
     * 删除收藏的简历
     */
    @ApiOperation(value = "删除收藏的简历")
    @GetMapping("/delete-collected")
    //@Anonymous
    public ResponseEntity<String> deleteCollectedResume(
            @ApiParam(value = "简历ID", required = true) @RequestParam int resumeId
    ) {
        resumeService.deleteCollectedResume(resumeId);


        return ResponseEntity.ok("删除成功");
    }

    /**
     * 修改简历的内外部状态
     */
    @ApiOperation(value = "修改简历的内外部状态")
    @GetMapping("/update-status")
    @Anonymous
    public ResponseEntity<String> updateResumeStatus(
            @ApiParam(value = "简历ID", required = true) @RequestParam int resumeId,
            @ApiParam(value = "内外部状态", required = true) @RequestParam int status
    ) {
        resumeService.updateResumeStatus(resumeId, status);
        return ResponseEntity.ok("修改成功");
    }

    @ApiOperation(value = "根据简历ID获取简历内容")
    @GetMapping("/content-by-id")
    @Anonymous
    public ResponseEntity<SplitResumeResult> getResumeContentById(
            @ApiParam(value = "简历ID", required = true) @RequestParam int resumeId
    ) {
        SplitResumeResult content = resumeService.getResumeContentById(resumeId);
        if (content != null) {
            return ResponseEntity.ok(content);
        } else {
            return ResponseEntity.status(HttpServletResponse.SC_NOT_FOUND).body(null);
        }
    }

    @ApiOperation(value = "根据简历ID获取简历文件,返回URL")
    @GetMapping("/file-by-id")
    @Anonymous
    public ResponseEntity<String> getResumeFileById(
            @ApiParam(value = "简历ID", required = true) @RequestParam int resumeId
    ) {
        try {
            String url = resumeService.getResumeFileById(resumeId);
            return ResponseEntity.ok(url);
        } catch (Exception e) {
//            log.error("Failed to fetch file for resumeId {}: {}", resumeId, e.getMessage());
            return ResponseEntity.status(HttpServletResponse.SC_NOT_FOUND).body(null);
        }
    }

    @ApiOperation(value = "根据简历ID删除简历")
    @DeleteMapping("/delete-by-id")
    @Anonymous
    public ResponseEntity<String> deleteResumeById(
            @ApiParam(value = "简历ID", required = true) @RequestParam int resumeId
    ) throws Exception {
        resumeService.deleteResumeById(resumeId);
        return ResponseEntity.ok("删除成功");
    }

    @ApiOperation(value = "更新简历信息")
    @PostMapping("/update")
    @Anonymous
    public ResponseEntity<SplitResumeResult> updateResume(
            @ApiParam(value = "简历ID", required = true) @RequestParam int resumeId,
            @ApiParam(value = "简历内容", required = true) @RequestBody SplitResumeResult resumeDetailsResponse
    ) {
        resumeService.updateResume(resumeId, resumeDetailsResponse);
        return ResponseEntity.ok(resumeDetailsResponse);
    }

    @ApiOperation(value = "查询简历基本信息")
    @GetMapping("/getBasicInfo")
    @Anonymous
    public ResponseEntity<BasicInfo> getResumeBasicInfo(
            @ApiParam(value = "简历ID", required = true) @RequestParam int resumeId
    ) {
        BasicInfo basicInfo = resumeService.getBasicInfoByResumeId(resumeId); // 调用服务层方法获取基本信息
        return basicInfo != null
                ? ResponseEntity.ok(basicInfo)
                : ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
    }

    @ApiOperation(value = "查询相似候选人基本信息")
    @GetMapping("/getSimilarCandidates")
    @Anonymous
    public ResponseEntity<List<SimilarCandidateResp>> getSimilarCandidates(
            @ApiParam(value = "简历ID", required = true) @RequestParam int resumeId
    ) {
        // 调用服务层方法获取相似候选人的基本信息列表
        List<SimilarCandidateResp> similarCandidates = resumeService.getSimilarCandidatesByResumeId(resumeId);

        // 如果有相似候选人，返回信息；否则返回404
        return similarCandidates != null && !similarCandidates.isEmpty()
                ? ResponseEntity.ok(similarCandidates)
                : ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
    }

    @ApiOperation(value = "根据标签查询符合的简历")
    @GetMapping("/getResumesByTags")
    @Anonymous
    public TableDataInfo getResumesByTags(
            @ApiParam(value = "标签列表", required = true) @RequestParam List<String> tags
    ) {
        startPage();
        // 调用服务层方法获取符合标签的简历列表
        return resumeService.getResumesByTags(tags);

        // 如果有符合的简历，返回信息；否则返回404
        /*return matchingResumes != null && !matchingResumes.isEmpty()
                ? ResponseEntity.ok(matchingResumes)
                : ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);*/
    }

    @ApiOperation(value = "获取最新导入的10条简历动态")
    @GetMapping("/getLatestResumes")
    @Anonymous
    public ResponseEntity<List<ResumeAndTagsResp>> getLatestResumes() {
        List<ResumeAndTagsResp> latestResumes = resumeService.getLatestResumes();
        return latestResumes != null && !latestResumes.isEmpty()
                ? ResponseEntity.ok(latestResumes)
                : ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
    }


    /**
     * 获取人才地图
     * */
    @ApiOperation(value = "获取人才地图")
    @GetMapping("/getTalentMap")
    @Anonymous
    public ResponseEntity<List<Mappings>> getTalentMap() {
        List<Mappings> talentMap = resumeService.getTalentMap();
        return talentMap != null && !talentMap.isEmpty()
                ? ResponseEntity.ok(talentMap)
                : ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
    }




}
